package cn.devmgr.tutorial;


import org.jinterop.dcom.common.JIException;
import org.openscada.opc.lib.common.AlreadyConnectedException;
import org.openscada.opc.lib.common.ConnectionInformation;
import org.openscada.opc.lib.da.Server;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.UnknownHostException;
import java.util.concurrent.Executors;


@Service
public class OPCService {

    @Autowired
    OPCConfig opcConfig;

    private Server server ;


    public Server openServer(){
        final ConnectionInformation ci = new ConnectionInformation();
        ci.setHost(opcConfig.getHost());         // 电脑IP
        ci.setDomain("");                  // 域，为空就行
        ci.setUser(opcConfig.getUser());             // 电脑上自己建好的用户名
        ci.setPassword(opcConfig.getPassword());

        ci.setClsid(opcConfig.getClsId());
        // 启动服务
        final Server server = new org.openscada.opc.lib.da.Server(ci, Executors.newSingleThreadScheduledExecutor());

        try {
            // 连接到服务
            server.connect();
            this.server = server;
            return server;
        } catch (final JIException e) {
            System.out.println(String.format("%08X: %s", e.getErrorCode(), server.getErrorMessage(e.getErrorCode())));
        } catch (AlreadyConnectedException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return server;
    }

    public Server getServer() {
        return server;
    }

    public void disServer(){
        server.disconnect();
        return;
    }

}
